package com.mineoj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mineoj.common.ErrorCode;
import com.mineoj.exception.BusinessException;
import com.mineoj.model.dto.questionlisttitle.QuestionListTitleAddRequest;
import com.mineoj.model.entity.QuestionList;
import com.mineoj.model.entity.QuestionListTitle;
import com.mineoj.model.entity.User;
import com.mineoj.service.QuestionListService;
import com.mineoj.service.QuestionListTitleService;
import com.mineoj.mapper.QuestionListTitleMapper;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
* @author 明月
* @description 针对表【question_list_title(题单题目)】的数据库操作Service实现
* @createDate 2025-04-05 16:35:05
*/
@Service
public class QuestionListTitleServiceImpl extends ServiceImpl<QuestionListTitleMapper, QuestionListTitle>
    implements QuestionListTitleService{


    @Resource
    private QuestionListService questionListService;

    /**
     * 校验题目能不能添加到题单
     * @param questionListTitleAddRequest
     * @return true  已经存在
     *         false 不存在
     */
    @Override
    public boolean validQuestionListTitle(QuestionListTitleAddRequest questionListTitleAddRequest) {
        if (questionListTitleAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (questionListTitleAddRequest.getQuestionListId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "题单不存在");
        }
        if (questionListTitleAddRequest.getQuestionId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "题目不存在");
        }


        // 判断题单里是否有对于题目
        QuestionListTitle questionListTitle = new QuestionListTitle();
        questionListTitle.setQuestionListId(questionListTitleAddRequest.getQuestionListId());
        questionListTitle.setQuestionId(questionListTitleAddRequest.getQuestionId());
        if (this.getOne(new QueryWrapper<>(questionListTitle)) != null) {
            return true;
        }
        return false;
    }

    /**
     * 添加题目到题单
     * @param questionListTitleAddRequest
     * @param loginUser
     * @return
     */
    @Override
    public int addQuestionListTitle(QuestionListTitleAddRequest questionListTitleAddRequest, User loginUser) {
        // 校验题目能不能添加到题单
        boolean flag = this.validQuestionListTitle(questionListTitleAddRequest);

        // 是否已点赞
        long userId = loginUser.getId();
        // 每个用户串行点赞
        // 锁必须要包裹住事务方法
        QuestionListTitleService questionListThumbService = (QuestionListTitleService) AopContext.currentProxy();
        synchronized (String.valueOf(userId).intern()) {
            return questionListThumbService.addQuestionListTitleInner(userId, questionListTitleAddRequest, flag);
        }
    }

    /**
     * 封装了事务的方法
     * @param userId
     * @param questionListTitleAddRequest
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addQuestionListTitleInner(long userId, QuestionListTitleAddRequest questionListTitleAddRequest, boolean add) {
        QuestionListTitle questionListTitle = new QuestionListTitle();
        questionListTitle.setUserId(userId);
        questionListTitle.setQuestionListId(questionListTitleAddRequest.getQuestionListId());
        questionListTitle.setQuestionId(questionListTitleAddRequest.getQuestionId());

        QueryWrapper<QuestionListTitle> titleQueryWrapper = new QueryWrapper<>(questionListTitle);
        boolean result;
        // 已存在
        if (add) {
            result = this.remove(titleQueryWrapper);
            if (result) {
                // 题目数 - 1
                result = questionListService.update()
                        .eq("id", questionListTitle.getQuestionListId())
                        .gt("questionNum", 0)
                        .setSql("questionNum = questionNum - 1")
                        .update();
                return result ? -1 : 0;
            } else {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        } else {
            // 未存在
            result = this.save(questionListTitle);
            if (result) {
                // 点赞数 + 1
                result = questionListService.update()
                        .eq("id", questionListTitle.getQuestionListId())
                        .setSql("questionNum = questionNum + 1")
                        .update();
                return result ? 1 : 0;
            } else {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        }
    }
}




